import * as vscode from 'vscode';
import { ApiService } from './api';
import { MCPServer } from './models';
import { MCPServerTreeProvider, InstalledMCPServerTreeProvider } from './tree-view';

export async function activate(context: vscode.ExtensionContext) {
  console.log('MCPRepoMarket 扩展已激活');

  // 创建API服务
  const apiService = new ApiService(context);

  // 创建树视图提供器
  const mcpServerTreeProvider = new MCPServerTreeProvider(apiService);
  const installedMCPServerTreeProvider = new InstalledMCPServerTreeProvider(apiService);

  // 注册树视图
  const serversTreeView = vscode.window.createTreeView('mcphubServers', {
    treeDataProvider: mcpServerTreeProvider,
    showCollapseAll: false
  });

  const installedServersTreeView = vscode.window.createTreeView('mcphubInstalledServers', {
    treeDataProvider: installedMCPServerTreeProvider,
    showCollapseAll: false
  });

  context.subscriptions.push(serversTreeView);
  context.subscriptions.push(installedServersTreeView);

  // 注册命令
  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.refreshServerList', () => {
      mcpServerTreeProvider.refresh();
      installedMCPServerTreeProvider.refresh();
      vscode.window.showInformationMessage('MCP Server 列表已刷新');
    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.viewInstalledServers', () => {
      installedMCPServerTreeProvider.refresh();
    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.searchServers', async () => {
      const query = await vscode.window.showInputBox({
        placeHolder: '输入搜索关键词',
        prompt: '搜索MCP Server '
      });

      if (query !== undefined) {
        mcpServerTreeProvider.updateSearchQuery(query);
      }
    })
  );

  // 新增 - 筛选服务器命令
  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.filterServers', async () => {
      const filters = [
        { label: '全部', description: '显示所有MCP Server', filterValue: 'all' },
        { label: '内部', description: '仅显示内部MCP Server', filterValue: 'internal' },
        { label: '开源', description: '仅显示开源MCP Server', filterValue: 'opensource' },
        { label: 'Python', description: '仅显示Python MCP Server', filterValue: 'python' },
        { label: 'JavaScript', description: '仅显示JavaScript MCP Server', filterValue: 'javascript' },
        { label: 'Java', description: '仅显示Java MCP Server', filterValue: 'java' }
      ];

      const selectedFilter = await vscode.window.showQuickPick(filters, {
        placeHolder: '选择筛选条件'
      });

      if (selectedFilter) {
        // 设置筛选条件
        mcpServerTreeProvider.updateFilter(selectedFilter.filterValue);
        vscode.window.showInformationMessage(`已筛选: ${selectedFilter.label}`);
      }
    })
  );

  // 新增 - 排序服务器命令
  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.sortServers', async () => {
      const sortOptions = [
        { label: '按名称排序', description: '按MCP Server名称字母顺序排序', sortKey: 'name' },
        { label: '按安装量排序', description: '按MCP Server安装量排序', sortKey: 'installs' },
        { label: '按更新时间排序', description: '按MCP Server更新时间排序', sortKey: 'updated' }
      ];

      const selectedOption = await vscode.window.showQuickPick(sortOptions, {
        placeHolder: '选择排序方式'
      });

      if (selectedOption) {
        // 设置排序方式
        mcpServerTreeProvider.updateSortOrder(selectedOption.sortKey);
        vscode.window.showInformationMessage(`已排序: ${selectedOption.label}`);
      }
    })
  );

  // 新增 - 打开设置页面
  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.openSettingsPage', () => {
      vscode.commands.executeCommand('workbench.action.openSettings', 'mcphub');
    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.installServer', async (server: MCPServer) => {
      try {
        // 如果 Server 没有安装命令或提示词，先获取详情
        if (!server.installCommands || !server.installPrompt) {
          try {
            server = await apiService.getMCPServerDetail(server.id);
          } catch (error) {
            vscode.window.showErrorMessage(`无法获取MCP Server详情: ${error}`);
            return;
          }
        }

        // 先显示安装提示词弹窗
        if (server.installPrompt) {
          const installPromptBox = vscode.window.createWebviewPanel(
            'mcpServerInstallPrompt',
            `安装 ${server.name}`,
            vscode.ViewColumn.One,
            {
              enableScripts: true,
              retainContextWhenHidden: false
            }
          );

          installPromptBox.webview.html = `
            <!DOCTYPE html>
            <html lang="zh-CN">
            <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>安装提示</title>
              <style>
                body {
                  font-family: var(--vscode-font-family);
                  color: var(--vscode-foreground);
                  background-color: var(--vscode-editor-background);
                  padding: 20px;
                  line-height: 1.6;
                }
                .container {
                  max-width: 800px;
                  margin: 0 auto;
                  border-radius: 8px;
                  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
                  overflow: hidden;
                }
                h2 {
                  border-bottom: 1px solid var(--vscode-panel-border);
                  padding: 16px 20px;
                  margin: 0;
                  background: var(--vscode-editor-inactiveSelectionBackground);
                }
                .prompt {
                  background-color: var(--vscode-editor-background);
                  padding: 20px;
                  border-radius: 5px;
                  margin: 15px;
                  white-space: pre-wrap;
                  border-left: 4px solid var(--vscode-activityBarBadge-background);
                }
                .button-container {
                  display: flex;
                  justify-content: flex-end;
                  gap: 10px;
                  margin-top: 20px;
                  padding: 0 20px 20px;
                }
                button {
                  background-color: var(--vscode-button-background);
                  color: var(--vscode-button-foreground);
                  border: none;
                  padding: 8px 16px;
                  border-radius: 4px;
                  cursor: pointer;
                  transition: all 0.2s ease;
                }
                button:hover {
                  background-color: var(--vscode-button-hoverBackground);
                  transform: translateY(-2px);
                }
                .cancel {
                  background-color: var(--vscode-button-secondaryBackground);
                  color: var(--vscode-button-secondaryForeground);
                }
              </style>
            </head>
            <body>
              <div class="container">
                <h2>安装 ${server.name}</h2>
                <div class="prompt">${server.installPrompt}</div>
                <div class="button-container">
                  <button class="cancel" id="cancelButton">取消</button>
                  <button id="installButton">继续安装</button>
                </div>
              </div>
              <script>
                const vscode = acquireVsCodeApi();
                document.getElementById('installButton').addEventListener('click', () => {
                  vscode.postMessage({ command: 'continue' });
                });
                document.getElementById('cancelButton').addEventListener('click', () => {
                  vscode.postMessage({ command: 'cancel' });
                });
              </script>
            </body>
            </html>
          `;

          // 处理用户选择
          const result = await new Promise<string>((resolve) => {
            installPromptBox.webview.onDidReceiveMessage(
              message => {
                resolve(message.command);
              },
              undefined
            );
            
            // 如果用户关闭面板，视为取消
            installPromptBox.onDidDispose(() => {
              resolve('cancel');
            });
          });

          // 关闭弹窗
          installPromptBox.dispose();
          
          // 如果用户取消，退出安装流程
          if (result === 'cancel') {
            return;
          }
        }

        // 显示安装命令选择
        let installCommand = '';
        if (server.installCommands && server.installCommands.length > 0) {
          const selectedCommand = await vscode.window.showQuickPick(
            server.installCommands.map(cmd => ({
              label: cmd.name,
              description: cmd.command,
              command: cmd.command
            })),
            {
              placeHolder: '选择安装命令'
            }
          );

          if (!selectedCommand) {
            return;
          }

          installCommand = selectedCommand.command;
        } else {
          vscode.window.showWarningMessage(`MCP Server ${server.name} 没有提供安装命令`);
          return;
        }

        // 执行安装命令
        const terminal = vscode.window.createTerminal(`安装 MCP Server: ${server.name}`);
        terminal.show();
        terminal.sendText(installCommand);

        // 保存为已安装
        await apiService.installMCPServer(server);
        
        // 刷新视图
        mcpServerTreeProvider.refresh();
        installedMCPServerTreeProvider.refresh();
        
        vscode.window.showInformationMessage(`MCP Server ${server.name} 安装命令已执行，请在终端中查看安装进度`);
      } catch (error) {
        vscode.window.showErrorMessage(`安装MCP Server ${server.name} 失败: ${error}`);
      }
    })
  );

  context.subscriptions.push(
    vscode.commands.registerCommand('mcphub.openServerDetails', async (server: MCPServer) => {
      if (!server || !server.id) {
        vscode.window.showErrorMessage('无效的Server数据');
        return;
      }

      try {
        // 创建和显示详情面板
        const panel = vscode.window.createWebviewPanel(
          'mcpServerDetail',
          `MCP Server: ${server.name}`,
          vscode.ViewColumn.One,
          {
            enableScripts: true,
            retainContextWhenHidden: true,
            localResourceRoots: [
              vscode.Uri.joinPath(context.extensionUri, 'resources')
            ]
          }
        );

        // 先显示加载中状态
        panel.webview.html = getLoadingWebviewContent(server.name);

        // 获取完整的 Server 信息
        let detailedServer: MCPServer;
        try {
          detailedServer = await apiService.getMCPServerDetail(server.id);
        } catch (error) {
          console.error(`获取服务器详情失败: ${error}`);
          panel.webview.html = getErrorWebviewContent(server.name, `无法加载详情: ${error}`);
          return;
        }
        
        // 获取README内容
        let readmeContent = '';
        try {
          readmeContent = await apiService.getMCPServerReadme(server.id);
        } catch (error) {
          console.error(`获取README失败: ${error}`);
          readmeContent = `无法加载README: ${error}`;
        }

        // 设置详情页面内容
        panel.webview.html = getWebviewContent(detailedServer, readmeContent);

        // 监听消息
        panel.webview.onDidReceiveMessage(
          async message => {
            switch (message.command) {
              case 'install':
                await vscode.commands.executeCommand('mcphub.installServer', detailedServer);
                break;
              case 'openBrowser':
                await apiService.openServerInBrowser(detailedServer);
                break;
              case 'search':
                if (message.query) {
                  mcpServerTreeProvider.updateSearchQuery(message.query);
                  vscode.window.showInformationMessage(`正在搜索: ${message.query}`);
                }
                break;
            }
          },
          undefined,
          context.subscriptions
        );
      } catch (error) {
        vscode.window.showErrorMessage(`打开MCP Server详情失败: ${error}`);
      }
    })
  );

  // 启动时自动刷新服务器列表
  mcpServerTreeProvider.refresh();
  installedMCPServerTreeProvider.refresh();
}

function getLoadingWebviewContent(serverName: string): string {
  return `<!DOCTYPE html>
  <html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>正在加载...</title>
    <style>
      body {
        font-family: var(--vscode-font-family);
        color: var(--vscode-foreground);
        background-color: var(--vscode-editor-background);
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
        margin: 0;
        padding: 20px;
        box-sizing: border-box;
      }
      .loading-container {
        text-align: center;
      }
      .spinner {
        width: 50px;
        height: 50px;
        border: 5px solid var(--vscode-button-background);
        border-radius: 50%;
        border-top-color: transparent;
        animation: spin 1s linear infinite;
        margin: 0 auto 20px;
      }
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      h2 {
        margin: 0;
      }
    </style>
  </head>
  <body>
    <div class="loading-container">
      <div class="spinner"></div>
      <h2>正在加载 ${serverName} 的详细信息...</h2>
    </div>
  </body>
  </html>`;
}

function getErrorWebviewContent(serverName: string, errorMessage: string): string {
  return `<!DOCTYPE html>
  <html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>错误</title>
    <style>
      body {
        font-family: var(--vscode-font-family);
        color: var(--vscode-foreground);
        background-color: var(--vscode-editor-background);
        padding: 20px;
      }
      .error-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        min-height: 80vh;
        text-align: center;
      }
      .error-icon {
        color: var(--vscode-errorForeground);
        font-size: 48px;
        margin-bottom: 16px;
      }
      .error-message {
        background-color: var(--vscode-inputValidation-errorBackground);
        color: var(--vscode-inputValidation-errorForeground);
        border: 1px solid var(--vscode-inputValidation-errorBorder);
        padding: 15px 20px;
        border-radius: 5px;
        margin-top: 20px;
        max-width: 600px;
      }
    </style>
  </head>
  <body>
    <div class="error-container">
      <div class="error-icon">⚠️</div>
      <h2>无法加载 ${serverName} 的详细信息</h2>
      <div class="error-message">${errorMessage}</div>
    </div>
  </body>
  </html>`;
}

function getWebviewContent(server: MCPServer, readmeContent: string): string {
  const installButton = !server.installed 
    ? `<button id="installButton" class="action-button">安装 Server</button>`
    : `<span class="installed-label">已安装</span>`;
    
  return `<!DOCTYPE html>
  <html lang="zh-CN">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCP Server: ${server.name}</title>
    <style>
      :root {
        --content-padding: 20px;
        --card-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        --card-radius: 8px;
        --tag-radius: 20px;
      }
      
      body {
        font-family: var(--vscode-font-family);
        color: var(--vscode-foreground);
        background-color: var(--vscode-editor-background);
        padding: 0;
        margin: 0;
        line-height: 1.6;
      }
      
      * {
        box-sizing: border-box;
      }
      
      .container {
        max-width: 1100px;
        margin: 0 auto;
        padding: var(--content-padding);
      }

      .header {
        display: flex;
        flex-direction: column;
        position: sticky;
        top: 0;
        background-color: var(--vscode-editor-background);
        padding: 16px var(--content-padding);
        margin-bottom: 20px;
        border-bottom: 1px solid var(--vscode-panel-border);
        z-index: 100;
      }
      
      .header-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
      }
      
      .search-container {
        display: flex;
        width: 100%;
        margin-top: 10px;
      }
      
      .search-input {
        flex: 1;
        background-color: var(--vscode-input-background);
        color: var(--vscode-input-foreground);
        border: 1px solid var(--vscode-input-border);
        padding: 6px 10px;
        border-radius: 4px;
        outline: none;
      }
      
      .search-input:focus {
        border-color: var(--vscode-focusBorder);
      }
      
      .search-button {
        background-color: var(--vscode-button-background);
        color: var(--vscode-button-foreground);
        border: none;
        margin-left: 8px;
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
      }
      
      .title {
        font-size: 26px;
        margin: 0;
        font-weight: bold;
        display: flex;
        align-items: center;
      }
      
      .title-version {
        font-size: 14px;
        color: var(--vscode-descriptionForeground);
        margin-left: 10px;
        font-weight: normal;
      }
      
      .description {
        color: var(--vscode-descriptionForeground);
        margin: 16px 0;
        font-size: 15px;
        line-height: 1.6;
      }
      
      .tags-container {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 20px;
      }
      
      .tag {
        display: inline-flex;
        align-items: center;
        background: linear-gradient(135deg, var(--vscode-badge-background), color-mix(in srgb, var(--vscode-badge-background), transparent 40%));
        color: var(--vscode-badge-foreground);
        padding: 4px 12px;
        border-radius: var(--tag-radius);
        font-size: 12px;
        font-weight: 500;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
      
      .tag.internal {
        background: linear-gradient(135deg, var(--vscode-activityBarBadge-background), color-mix(in srgb, var(--vscode-activityBarBadge-background), transparent 40%));
        color: var(--vscode-activityBarBadge-foreground);
      }
      
      .action-buttons {
        display: flex;
        gap: 10px;
      }
      
      .action-button {
        background: linear-gradient(to bottom, var(--vscode-button-background), color-mix(in srgb, var(--vscode-button-background), black 15%));
        color: var(--vscode-button-foreground);
        border: none;
        padding: 8px 16px;
        cursor: pointer;
        border-radius: 4px;
        font-weight: 500;
        display: flex;
        align-items: center;
        transition: all 0.2s ease;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
      }
      
      .action-button:hover {
        background: linear-gradient(to bottom, color-mix(in srgb, var(--vscode-button-background), white 10%), var(--vscode-button-background));
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
      }
      
      .installed-label {
        background-color: var(--vscode-badge-background);
        color: var(--vscode-badge-foreground);
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 13px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
      
      .main-content {
        display: grid;
        grid-template-columns: 300px 1fr;
        gap: 20px;
      }
      
      @media (max-width: 768px) {
        .main-content {
          grid-template-columns: 1fr;
        }
      }
      
      .info-card {
        background-color: var(--vscode-editor-inactiveSelectionBackground);
        border-radius: var(--card-radius);
        padding: 16px;
        margin-bottom: 20px;
        box-shadow: var(--card-shadow);
      }
      
      .info-grid {
        display: grid;
        grid-template-columns: auto 1fr;
        gap: 10px;
        margin-bottom: 16px;
      }
      
      .info-label {
        font-weight: 600;
        color: var(--vscode-editorInfo-foreground);
      }
      
      .section-title {
        font-size: 18px;
        margin: 24px 0 16px 0;
        padding-bottom: 8px;
        border-bottom: 1px solid var(--vscode-panel-border);
        font-weight: 600;
      }
      
      .install-commands-list {
        list-style: none;
        padding: 0;
        margin: 0;
      }
      
      .install-command-item {
        background-color: var(--vscode-editor-inactiveSelectionBackground);
        padding: 12px;
        border-radius: 4px;
        margin-bottom: 8px;
      }
      
      .install-command-name {
        font-weight: 600;
        margin-bottom: 6px;
        color: var(--vscode-editorInfo-foreground);
      }
      
      .install-command-code {
        background-color: var(--vscode-textCodeBlock-background);
        color: var(--vscode-textPreformat-foreground);
        padding: 8px 10px;
        border-radius: 4px;
        font-family: var(--vscode-editor-font-family), monospace;
        font-size: 13px;
        overflow-x: auto;
        white-space: pre-wrap;
      }
      
      .config-json {
        background-color: var(--vscode-textBlockQuote-background);
        padding: 16px;
        border-left: 3px solid var(--vscode-textBlockQuote-border);
        overflow: auto;
        font-family: var(--vscode-editor-font-family), monospace;
        font-size: 13px;
        border-radius: 4px;
        margin-top: 12px;
      }
      
      .readme-container {
        background-color: var(--vscode-editor-inactiveSelectionBackground);
        border-radius: var(--card-radius);
        overflow: hidden;
        box-shadow: var(--card-shadow);
      }
      
      .readme-header {
        background-color: var(--vscode-activityBarBadge-background);
        color: var(--vscode-activityBarBadge-foreground);
        padding: 10px 16px;
        font-weight: 600;
        font-size: 16px;
      }
      
      .readme-content {
        padding: 20px;
        line-height: 1.6;
      }
      
      /* Markdown 样式 */
      .markdown-body {
        font-family: var(--vscode-font-family);
        font-size: 14px;
        line-height: 1.6;
        word-wrap: break-word;
      }
      
      .markdown-body h1, 
      .markdown-body h2,
      .markdown-body h3, 
      .markdown-body h4, 
      .markdown-body h5, 
      .markdown-body h6 {
        margin-top: 24px;
        margin-bottom: 16px;
        font-weight: 600;
        line-height: 1.25;
      }
      
      .markdown-body h1 {
        font-size: 1.5em;
        padding-bottom: 0.3em;
        border-bottom: 1px solid var(--vscode-panel-border);
      }
      
      .markdown-body h2 {
        font-size: 1.3em;
        padding-bottom: 0.3em;
        border-bottom: 1px solid var(--vscode-panel-border);
      }
      
      .markdown-body p {
        margin-top: 0;
        margin-bottom: 16px;
      }
      
      .markdown-body a {
        color: var(--vscode-textLink-foreground);
        text-decoration: none;
      }
      
      .markdown-body a:hover {
        text-decoration: underline;
      }
      
      .markdown-body img {
        max-width: 100%;
        box-sizing: border-box;
      }
      
      .markdown-body code {
        font-family: var(--vscode-editor-font-family), monospace;
        padding: 0.2em 0.4em;
        margin: 0;
        font-size: 85%;
        background-color: var(--vscode-textCodeBlock-background);
        border-radius: 3px;
      }
      
      .markdown-body pre {
        background-color: var(--vscode-textCodeBlock-background);
        border-radius: 6px;
        padding: 16px;
        overflow: auto;
        font-size: 85%;
        line-height: 1.45;
        margin-bottom: 16px;
      }
      
      .markdown-body pre code {
        background-color: transparent;
        padding: 0;
        margin: 0;
        font-size: 100%;
        word-break: normal;
        white-space: pre;
        background: transparent;
        border: 0;
      }
      
      .markdown-body blockquote {
        padding: 0 1em;
        color: var(--vscode-descriptionForeground);
        border-left: 0.25em solid var(--vscode-panel-border);
        margin: 0 0 16px 0;
      }
      
      .markdown-body ul,
      .markdown-body ol {
        padding-left: 2em;
        margin-top: 0;
        margin-bottom: 16px;
      }
      
      .markdown-body table {
        border-spacing: 0;
        border-collapse: collapse;
        margin-top: 0;
        margin-bottom: 16px;
        width: 100%;
        overflow: auto;
      }
      
      .markdown-body table th {
        font-weight: 600;
        padding: 6px 13px;
        background-color: var(--vscode-editor-inactiveSelectionBackground);
        border: 1px solid var(--vscode-panel-border);
      }
      
      .markdown-body table td {
        padding: 6px 13px;
        border: 1px solid var(--vscode-panel-border);
      }
      
      .markdown-body hr {
        height: 0.25em;
        padding: 0;
        margin: 24px 0;
        background-color: var(--vscode-panel-border);
        border: 0;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  </head>
  <body>
    <div class="header">
      <div class="header-top">
        <h1 class="title">${server.name} <span class="title-version">v${server.version || '1.0.0'}</span></h1>
        <div class="action-buttons">
          ${installButton}
          <button id="openBrowserButton" class="action-button">在浏览器中查看</button>
        </div>
      </div>
      <div class="search-container">
        <input id="searchInput" class="search-input" placeholder="搜索其他 MCP Server..." type="text">
        <button id="searchButton" class="search-button">搜索</button>
      </div>
    </div>

    <div class="container">
      <div class="tags-container">
        ${server.isInternal ? '<span class="tag internal">内部</span>' : '<span class="tag">开源</span>'}
        ${server.language ? `<span class="tag">${server.language}</span>` : ''}
        ${server.authType ? `<span class="tag">${server.authType}</span>` : ''}
      </div>

      <p class="description">${server.description}</p>

      <div class="main-content">
        <div class="info-sidebar">
          <div class="info-card">
            <div class="info-grid">
              <span class="info-label">作者:</span>
              <span>${server.author || '未知'}</span>
              
              <span class="info-label">GitHub:</span>
              <span>${server.github || '未提供'}</span>
            </div>
          </div>

          ${server.installCommands && server.installCommands.length > 0 ? `
          <div class="info-card">
            <h2 class="section-title">安装命令</h2>
            <ul class="install-commands-list">
              ${server.installCommands.map(cmd => `
                <li class="install-command-item">
                  <div class="install-command-name">${cmd.name}</div>
                  <div class="install-command-code">${cmd.command}</div>
                </li>
              `).join('')}
            </ul>
          </div>
          ` : ''}

          ${server.configJsonList && server.configJsonList.length > 0 ? `
          <div class="info-card">
            <h2 class="section-title">配置</h2>
            ${server.configJsonList.map(config => `
              <h3>${config.name}</h3>
              <pre class="config-json">${config.json}</pre>
            `).join('')}
          </div>
          ` : ''}
        </div>

        <div class="readme-container">
          <div class="readme-header">README</div>
          <div class="readme-content">
            <div id="markdown-content" class="markdown-body"></div>
          </div>
        </div>
      </div>
    </div>

    <script>
      const vscode = acquireVsCodeApi();
      
      // 渲染Markdown内容
      const readmeContent = ${JSON.stringify(readmeContent)};
      try {
        document.getElementById('markdown-content').innerHTML = marked.parse(readmeContent);
      } catch (error) {
        document.getElementById('markdown-content').textContent = readmeContent;
      }
      
      document.getElementById('openBrowserButton').addEventListener('click', () => {
        vscode.postMessage({
          command: 'openBrowser'
        });
      });
      
      ${!server.installed ? `
      document.getElementById('installButton').addEventListener('click', () => {
        vscode.postMessage({
          command: 'install'
        });
      });
      ` : ''}
      
      // 搜索功能
      document.getElementById('searchButton').addEventListener('click', () => {
        const query = document.getElementById('searchInput').value.trim();
        if (query) {
          vscode.postMessage({
            command: 'search',
            query: query
          });
        }
      });
      
      document.getElementById('searchInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          const query = document.getElementById('searchInput').value.trim();
          if (query) {
            vscode.postMessage({
              command: 'search',
              query: query
            });
          }
        }
      });
    </script>
  </body>
  </html>`;
}

export function deactivate() {} 